package hw.ats.news.activity.ats;

import hw.ats.news.R;
import hw.ats.common.model.Ats;
import hw.ats.news.activity.DBAwareActivity;
import hw.ats.news.ui.BottomTabHostProvider;
import hw.ats.news.ui.CommonUI;
import hw.ats.news.ui.NewsResourceHolder;
import hw.ats.news.util.App;
import hw.ats.news.util.DataLoader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.humanwares.ui.asyncimage.ImageDisplayer;
import com.humanwares.ui.asyncimage.ImageReceivedCallback;
import com.humanwares.ui.asyncimage.ImageReceiver;
import com.humanwares.ui.tabbar.TabHost;
import com.tattermedia.allthataudio.misc.DebugFlag;

public class AtsListAct extends DBAwareActivity implements ImageReceivedCallback {
	private final static String TAG = "AtsListAct";
	
	private List<Ats> allAts = null;
	private List<Ats> myAts = null;
	private Map<String, Ats> allAtsMap = null;
	private ListView listViewTab1 = null;
	private ListView listViewTab2 = null;
	private TabHost navbar = null;
	
	private DisplayMetrics dm = null;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        
        loadData();
        
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        
        setContentView(R.layout.act_ats_list);
        
        // 탭바 초기화
        navbar = CommonUI.renderTabBar(this, BottomTabHostProvider.TAB5);
		
		// 네이게이션바 제목
        CommonUI.renderAppTitle(this);
        
        // 좌측 네비게이션 버튼 = 이전화면 이동
        CommonUI.addLeftNavigationButtonBackEvent(this);
        
        // 우측 네비게이션 버튼 = All That 화면이동
        //CommonUI.addRightNavigationButtonAllThatEvent(this);
        
        android.widget.TabHost tabs = (android.widget.TabHost)findViewById(R.id.tabhost);
        tabs.setup();
        
        android.widget.TabHost.TabSpec spec = null;
        
        spec = tabs.newTabSpec("tag1");
        spec.setContent(R.id.ats_list_tab1);
        spec.setIndicator("올댓 시리즈 전체");
        tabs.addTab(spec);

        spec = tabs.newTabSpec("tag2");
        spec.setContent(R.id.ats_list_tab2);
        spec.setIndicator("내가 설치한 올댓");
        tabs.addTab(spec);
        
        tabs.getTabWidget().getChildAt(0).getLayoutParams().height = (int)(34 * dm.density);
        tabs.getTabWidget().getChildAt(1).getLayoutParams().height = (int)(34 * dm.density);
        
        // 탭 글꼴 크기 변경
        TabWidget tw = tabs.getTabWidget();
        for (int i=0; i<tw.getChildCount(); i++) {
            RelativeLayout relLayout = (RelativeLayout)tw.getChildAt(i);
            TextView tabTextView = (TextView)relLayout.getChildAt(1);
            tabTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
        } 
        
        List<String> pkgNames = DataLoader.findAllThatSeries(this);
        for (int i = 0, len = pkgNames.size(); i < len; i++) {
        	Log.d("AllThatNews", "pkgName="+pkgNames.get(i));
        }
        
		listViewTab1 = (ListView)findViewById(R.id.ats_list_tab1);
		listViewTab1.setAdapter(new AtsListAdapter(this, allAts));
		listViewTab1.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
			}
        });
		
		listViewTab2 = (ListView)findViewById(R.id.ats_list_tab2);
		listViewTab2.setAdapter(new AtsListAdapter(this, myAts));
		listViewTab2.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
			}
        });
    }
    
    @Override
	protected void onDestroy() {
		super.onDestroy();
		if (DebugFlag.isLogEnabled()) Log.d(TAG, "onDestroy()");
		closeDatabase();
	}
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        int visibility = navbar.getVisibility();
        navbar.setVisibility(visibility == View.VISIBLE ? View.INVISIBLE : View.VISIBLE);
        return false;
    }
    
    /**
     * 이미지 로더
     */
	public void onImageReceived(ImageDisplayer displayer) {
		this.runOnUiThread(displayer);
	}
	
    private void loadData() {
    	allAts = Ats.list(getReadableDatabase());
    	if (DebugFlag.isLogEnabled()) Log.d("allAts", "allAts="+allAts);
    	myAts = new ArrayList<Ats>();
    	allAtsMap = new HashMap<String, Ats>();
    	for (int i = 0, len = allAts.size(); i < len; i++) {
    		Ats ats = allAts.get(i);
    		allAtsMap.put(ats.pkg_name, ats);
    	}
    	
    	List<String> appList = DataLoader.findAllThatSeries(this);
    	for (String pkgName : appList) {
			Ats ats = allAtsMap.get(pkgName);
			if (ats != null) {
				myAts.add(ats);
			}
		}
    }
    
	private class AtsListAdapter extends BaseAdapter {
		private final static String TAG = "AtsListAdapter";
	   	private final Activity context;
	   	private List<Ats> items;

        public AtsListAdapter(Activity context, List<Ats> items) {
        	this.context = context;
        	this.items = items;
        }

        public int getCount() {
        	if (items == null)
        		return 0;
        	
        	return items.size();
        }

        public Object getItem(int position) {
            return items.get(position);
        }

        public long getItemId(int position) {
            return position;
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            NewsResourceHolder holder = null;
            if (view == null) {
            	LayoutInflater vi = context.getLayoutInflater();
            	view = vi.inflate(R.layout.row_news_type2, null);
                holder = new NewsResourceHolder(view);
                view.setTag(holder);
            } else {
            	holder = (NewsResourceHolder)view.getTag();
            }

            Ats entry = items.get(position);
    		if (entry == null) {
    			return view;
    		}
    		
            if (holder.imageView != null) {
            	holder.imageView.setTag(position);
            	holder.imageView.setImageBitmap(null);
                new ImageReceiver(entry.thumb, (ImageReceivedCallback)context, 
                		holder.imageView, getThumbPath(), position);
                
                if (DebugFlag.isLogEnabled()) 
                	Log.d(TAG,
                		"pos="+position+
                		" img="+holder.imageView+
                		" cv="+convertView+
                		" par="+parent);
            }
            
            if (holder.titleView != null)
            	holder.titleView.setText(entry.title);
            
            if (holder.detailView != null) {
            int len = entry.body.length();
            	if (len > 256) len = 256;
            	holder.detailView.setText(entry.body.substring(0, len));
            }
    		
    		return view;
        }
	}
}
